//
//  HBPageSegmentView.m
//  HBLibary
//
//  Created by Rambo on 2018/8/20.
//

#import "HBPageSegmentView.h"
#import "NSString+HBCategory.h"

@interface HBPageSegmentView ()

@property (nonatomic, strong) UIScrollView *scrollView;

@property (nonatomic, strong) NSArray *titleButtons;

@property (nonatomic, strong) UIView *selectLine;

@property (nonatomic, strong) UIView *bottomLine;

@property (nonatomic, copy) HBPageSegmentViewSelectPageBlock selectPageBlock;

@property (nonatomic, weak) NSLayoutConstraint *selectLinLayoutConstraintHeight;

@property (nonatomic, strong) NSMutableArray *selectLineLayoutConstraints;

@property (nonatomic, weak) NSLayoutConstraint *bottomLineLayoutConstraint;

@property (nonatomic, assign) CGFloat contentHeight;

@property (nonatomic, copy) NSArray *layoutConstaints_H;

@property (nonatomic, assign) CGFloat minMargin;

@property (nonatomic, assign) CGFloat tagWidth;

@end

@implementation HBPageSegmentView

/**
 快速创建 HBPageSegmentView
 
 @param titles 标题数组
 @param titleFont 标题字体大小
 @param minMargin 标题之间最小间隙
 @param  tagWidth 标签宽度（为0时代表字体宽度）
 @param complete 回调
 @return HBPageSegmentView对象
 */
- (instancetype)initWithTitles:(NSArray<NSString*>*)titles titleFont:(UIFont*)titleFont minMargin:(CGFloat)minMargin tagWidth:(CGFloat)tagWidth complete:(HBPageSegmentViewSelectPageBlock)complete{
    if (self = [super init]) {
        self.backgroundColor = [UIColor whiteColor];
        _selectLineColor = [UIColor redColor];
        _bottomLineColor = [UIColor lightGrayColor];
        _bottomLineHeight = 1.0f;
        _selectLineHeight = 2.0f;
        _selectButtonScaleMultiplier = 1.2f;
        _titleNormalColor = [UIColor lightGrayColor];
        _titleSelectColor = [UIColor redColor];
        _minMargin = minMargin;
        _tagWidth = tagWidth;
        
        self.bottomLine = ({
            UIView *line = [UIView new];
            line.backgroundColor = _bottomLineColor;
            [self addSubview:line];
            line.translatesAutoresizingMaskIntoConstraints = NO;
            
            NSArray *layoutConstraint_H = [NSLayoutConstraint constraintsWithVisualFormat:@"|[line]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(line)];
            [self addConstraints:layoutConstraint_H];
            
            NSArray *layoutConstraint_V = [NSLayoutConstraint constraintsWithVisualFormat:@"V:[line]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(line)];
            [self addConstraints:layoutConstraint_V];
            
            NSLayoutConstraint *layoutConstraintHeight = [NSLayoutConstraint constraintWithItem:line attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeHeight multiplier:1 constant:_bottomLineHeight];
            self.bottomLineLayoutConstraint = layoutConstraintHeight;
            [self addConstraint:layoutConstraintHeight];
            
            line;
        });
        
        self.scrollView = ({
            UIScrollView *scrollView = [[UIScrollView alloc] init];
            scrollView.showsHorizontalScrollIndicator = NO;
            scrollView.showsVerticalScrollIndicator = NO;
            [self addSubview:scrollView];
            
            scrollView.translatesAutoresizingMaskIntoConstraints = NO;
            
            NSArray *layoutConstraint_H = [NSLayoutConstraint constraintsWithVisualFormat:@"|[scrollView]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(scrollView)];
            [self addConstraints:layoutConstraint_H];
            
            NSArray *layoutConstraint_V = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|[scrollView]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(scrollView)];
            [self addConstraints:layoutConstraint_V];
            
            NSLayoutConstraint *layoutConstaintHeight = [NSLayoutConstraint constraintWithItem:scrollView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeHeight multiplier:1 constant:0];
            [self addConstraint:layoutConstaintHeight];
            
            scrollView;
        });
        
        
        
        if (titles && [titles isKindOfClass:[NSArray class]] && titles.count > 0) {
            
            //            self.titles = titles;
            
            self.selectPageBlock = complete;
            
            if (!titleFont) titleFont = [UIFont systemFontOfSize:16];
            
            CGFloat totalWidth = 0;
            
            for (NSInteger idx = 0; idx < titles.count; idx++) {
                NSString *title = titles[idx];
                if (![title isKindOfClass:[NSString class]]) continue;
                
                CGSize titleSize = [title boundingRectWithSize:CGSizeMake(MAXFLOAT, MAXFLOAT) options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading) attributes:@{NSFontAttributeName : titleFont} context:nil].size;
                if (_tagWidth > 0.0f) {
                    titleSize = CGSizeMake(_tagWidth, titleSize.height);
                }else{
                    titleSize = CGSizeMake(titleSize.width + 0.5, titleSize.height);
                }
                _contentHeight = MAX(_contentHeight, titleSize.height);
                
                
                totalWidth += titleSize.width;
            }
            
            CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
            
            CGFloat margin = (screenWidth - totalWidth) / (titles.count + 1);
            
            margin = MAX((int)margin, minMargin);
            
            NSMutableArray *titleButtons = [NSMutableArray arrayWithCapacity:titles.count];
            
            UIButton *lastButton = nil;
            UIButton *firstButton = nil;
            
            NSMutableArray *layoutConstaints_H = [NSMutableArray array];
            
            for (NSInteger idx = 0; idx < titles.count; idx++) {
                NSString *title = titles[idx];
                UIButton *button = [self createButtonWithTitle:title normalTitleColor:_titleNormalColor selectTitleColor:_titleSelectColor tag:idx font:titleFont];
                
                button.translatesAutoresizingMaskIntoConstraints = NO;
                [self.scrollView addSubview:button];
                
                if (idx == 0) firstButton = button;
                
                NSArray *layoutConstaint_V = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|[button]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(button)];
                [self.scrollView addConstraints:layoutConstaint_V];
                
                NSLayoutConstraint *layoutConstraintHeight = [NSLayoutConstraint constraintWithItem:button attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeHeight multiplier:1 constant:0];
                [self addConstraint:layoutConstraintHeight];
                
                if (_tagWidth > 0.0f) {
                    NSLayoutConstraint *layoutConstaint_W = [NSLayoutConstraint constraintWithItem:button attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeWidth multiplier:1 constant:(screenWidth/titles.count)];
                    [self.scrollView addConstraint:layoutConstaint_W];
                }
                
                
                if (lastButton) {
                    NSLayoutConstraint *layoutConstaint_H = [NSLayoutConstraint constraintWithItem:button attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:lastButton attribute:NSLayoutAttributeRight multiplier:1 constant:margin];
                    [self.scrollView addConstraint:layoutConstaint_H];
                    [layoutConstaints_H addObject:layoutConstaint_H];
                }else{
                    NSLayoutConstraint *layoutConstaint_H = [NSLayoutConstraint constraintWithItem:button attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.scrollView attribute:NSLayoutAttributeLeft multiplier:1 constant:margin];
                    [self.scrollView addConstraint:layoutConstaint_H];
                    [layoutConstaints_H addObject:layoutConstaint_H];
                }
                
                if (button) [titleButtons addObject:button];
                
                lastButton = button;
                
            }
            
            self.titleButtons = titleButtons.copy;
            
            if (lastButton) {
                NSLayoutConstraint *rightLayoutConstaint = [NSLayoutConstraint constraintWithItem:lastButton attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self.scrollView attribute:NSLayoutAttributeRight multiplier:1 constant:-margin];
                [self.scrollView addConstraint:rightLayoutConstaint];
                [layoutConstaints_H addObject:rightLayoutConstaint];
            }
            
            self.layoutConstaints_H = layoutConstaints_H.copy;
            
            self.selectLine = ({
                UIView *line = [UIView new];
                line.backgroundColor = _selectLineColor;
                line.translatesAutoresizingMaskIntoConstraints = NO;
                [self.scrollView addSubview:line];
                if (firstButton) {
                    firstButton.selected = YES;
                    NSLayoutConstraint *layoutConstraintW = [NSLayoutConstraint constraintWithItem:line attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:firstButton attribute:NSLayoutAttributeWidth multiplier:1 constant:0];
                    [self.scrollView addConstraint:layoutConstraintW];
                    
                    
                    NSLayoutConstraint *layoutConstraintB = [NSLayoutConstraint constraintWithItem:line attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:firstButton attribute:NSLayoutAttributeBottom multiplier:1 constant:0];
                    [self.scrollView addConstraint:layoutConstraintB];
                    
                    NSLayoutConstraint *layoutConstraintH = [NSLayoutConstraint constraintWithItem:line attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeHeight multiplier:1 constant:self.selectLineHeight];
                    self.selectLinLayoutConstraintHeight = layoutConstraintH;
                    [self.scrollView addConstraint:layoutConstraintH];
                    
                    NSLayoutConstraint *layoutConstraintL = [NSLayoutConstraint constraintWithItem:line attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:firstButton attribute:NSLayoutAttributeLeft multiplier:1 constant:0];
                    [self.scrollView addConstraint:layoutConstraintL];
                    
                    self.selectLineLayoutConstraints = [NSMutableArray arrayWithObjects:layoutConstraintW,layoutConstraintL, nil];
                    
                }
                
                line;
            });
            
            
        }
        
        self.selectButtonScaleMultiplier = 1.2f;
        
    }
    return self;
}

/**
 快速创建 HBPageSegmentView
 
 @param titles 标题数组
 @param titleFont 标题字体大小
 @param minMargin 标题之间最小间隙
 @param complete 回调
 @return HBPageSegmentView对象
 */
- (instancetype)initWithTitles:(NSArray<NSString*>*)titles titleFont:(UIFont*)titleFont minMargin:(CGFloat)minMargin complete:(HBPageSegmentViewSelectPageBlock)complete{
    
    return [self initWithTitles:titles titleFont:titleFont minMargin:minMargin tagWidth:0 complete:complete];
}


- (void)selectPageWithIndex:(NSInteger)index{
    if (index < 0) index = 0;
    
    if (self.titleButtons && self.titleButtons.count > 0 && index >= self.titleButtons.count) {
        index = self.titleButtons.count - 1;
    }
    
    for (UIButton *subButton in self.titleButtons) {
        
        if (![subButton isKindOfClass:[UIButton class]]) continue;
        
        subButton.selected = index == subButton.tag;
        subButton.transform = CGAffineTransformIdentity;
        
        if (index == subButton.tag) {
            
            if (self.scrollView.contentSize.width > self.frame.size.width) {
                CGFloat centerX = (self.frame.size.width - subButton.frame.size.width) * 0.5;
                CGFloat offsetX = subButton.frame.origin.x - centerX;
                if (offsetX < 0) {
                    offsetX = 0;
                }
                
                if (offsetX > (self.scrollView.contentSize.width - self.frame.size.width)) {
                    offsetX = self.scrollView.contentSize.width - self.frame.size.width;
                }
                [self.scrollView setContentOffset:CGPointMake(offsetX, 0) animated:YES];
            }
            
            [NSLayoutConstraint deactivateConstraints:self.selectLineLayoutConstraints];
            
            
            NSLayoutConstraint *layoutConstraintW = [NSLayoutConstraint constraintWithItem:self.selectLine attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:subButton attribute:NSLayoutAttributeWidth multiplier:1 constant:0];
            if (self.selectLineWidth > 0) {
                layoutConstraintW = [NSLayoutConstraint constraintWithItem:self.selectLine attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeWidth multiplier:1 constant:self.selectLineWidth];
            }
            
            [self.scrollView addConstraint:layoutConstraintW];
            
//            NSLayoutConstraint *layoutConstraintL = [NSLayoutConstraint constraintWithItem:self.selectLine attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:subButton attribute:NSLayoutAttributeLeft multiplier:1 constant:0];
            NSLayoutConstraint *layoutConstraintL = [NSLayoutConstraint constraintWithItem:self.selectLine attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:subButton attribute:NSLayoutAttributeCenterX multiplier:1 constant:0];
            
            [self.scrollView addConstraint:layoutConstraintL];
            
            self.selectLineLayoutConstraints = [NSMutableArray arrayWithObjects:layoutConstraintW,layoutConstraintL, nil];
            
            [UIView animateWithDuration:0.25 animations:^{
                [self setNeedsLayout];
                [self layoutIfNeeded];
                subButton.transform = CGAffineTransformScale(subButton.transform, self.selectButtonScaleMultiplier, self.selectButtonScaleMultiplier);
            }];
            
        }
        
    }
}

#pragma mark - 私有方法

- (UIButton*)createButtonWithTitle:(NSString*)title normalTitleColor:(UIColor*)normalTitleColor selectTitleColor:(UIColor*)selectTitleColor tag:(NSInteger)tag font:(UIFont*)font{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setTitle:title forState:UIControlStateNormal];
    [button setTitleColor:normalTitleColor forState:UIControlStateNormal];
    [button setTitleColor:selectTitleColor forState:UIControlStateSelected];
    [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    button.titleLabel.font = font;
    button.tag = tag;
    //    [self addSubview:button];
    return button;
}

#pragma mark - Action

- (void)buttonClick:(UIButton*)sender{
    [self selectPageWithIndex:sender.tag];
    if (self.selectPageBlock) {
        self.selectPageBlock(sender.tag);
    }
    
}

#pragma mark - set

- (void)setSelectLineColor:(UIColor *)selectLineColor{
    _selectLineColor = selectLineColor;
    self.selectLine.backgroundColor = _selectLineColor;
}

- (void)setBottomLineColor:(UIColor *)bottomLineColor{
    _bottomLineColor = bottomLineColor;
    self.bottomLine.backgroundColor = _bottomLineColor;
}

- (void)setBottomLineHeight:(CGFloat)bottomLineHeight{
    _bottomLineHeight = bottomLineHeight;
    self.bottomLineLayoutConstraint.constant = _bottomLineHeight;
    [self setNeedsLayout];
    [self layoutIfNeeded];
}

- (void)setSelectLineHeight:(CGFloat)selectLineHeight{
    _selectLineHeight = selectLineHeight;
    self.selectLinLayoutConstraintHeight.constant = _selectLineHeight;
    [self setNeedsLayout];
    [self layoutIfNeeded];
}

- (void)setSelectButtonScaleMultiplier:(CGFloat)selectButtonScaleMultiplier{
    if (selectButtonScaleMultiplier > 2.0f) {
        selectButtonScaleMultiplier = 2.0f;
    }else if (selectButtonScaleMultiplier < 1.0f){
        selectButtonScaleMultiplier = 1.0f;
    }
    _selectButtonScaleMultiplier = selectButtonScaleMultiplier;
    for (UIButton *subButton in self.scrollView.subviews) {
        if (![subButton isKindOfClass:[UIButton class]]) continue;
        if (!subButton.isSelected) continue;
        subButton.transform = CGAffineTransformScale(subButton.transform, self.selectButtonScaleMultiplier, self.selectButtonScaleMultiplier);
    }
}

- (void)setTitleNormalColor:(UIColor *)titleNormalColor{
    _titleNormalColor = titleNormalColor;
    for (UIButton *subButton in self.titleButtons) {
        if (![subButton isKindOfClass:[UIButton class]]) continue;
        [subButton setTitleColor:_titleNormalColor forState:UIControlStateNormal];
    }
}

- (void)setTitleSelectColor:(UIColor *)titleSelectColor{
    _titleSelectColor = titleSelectColor;
    for (UIButton *subButton in self.titleButtons) {
        if (![subButton isKindOfClass:[UIButton class]]) continue;
        [subButton setTitleColor:_titleSelectColor forState:UIControlStateSelected];
    }
}

- (CGSize)intrinsicContentSize{
    CGSize size = [super intrinsicContentSize];
    size.height = self.contentHeight;
    return size;
}

- (void)setSelectLineWidth:(CGFloat)selectLineWidth{
    _selectLineWidth = selectLineWidth;
}

- (void)setSelectLineJoinType:(HBPageSegmentViewSelectLineJoinType)selectLineJoinType{
    _selectLineJoinType = selectLineJoinType;
    if (_selectLineJoinType == HBPageSegmentViewSelectLineJoinTypeRound) {
        self.selectLine.layer.cornerRadius = self.selectLineHeight * 0.5;
    }else{
        self.selectLine.layer.cornerRadius = 0;
    }
}

- (void)updateTitle:(NSString*)title atIndex:(NSInteger)index{
    if (index >= self.titleButtons.count) return;
    if ([NSString hb_isEmpty:title]) return;
    UIButton *button = self.titleButtons[index];
    if ([title isEqualToString:button.titleLabel.text]) return;
    
    
    [button setTitle:title forState:UIControlStateNormal];
    
    [self updateButton];
    
}


- (void)updateButton{
    CGFloat totalWidth = 0;
    
    for (NSInteger idx = 0; idx < self.titleButtons.count; idx++) {
        UIButton *button =  self.titleButtons[idx];
        NSString *title = button.titleLabel.text;
        
        CGSize titleSize = [title boundingRectWithSize:CGSizeMake(MAXFLOAT, MAXFLOAT) options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading) attributes:@{NSFontAttributeName : button.titleLabel.font} context:nil].size;
        _contentHeight = MAX(_contentHeight, titleSize.height);
        if (_tagWidth > 0.0f) {
            titleSize = CGSizeMake(_tagWidth, titleSize.height);
        }else{
            titleSize = CGSizeMake(titleSize.width + 0.5, titleSize.height);
        }

        totalWidth += titleSize.width;
    }
    
    CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
    
    CGFloat margin = (screenWidth - totalWidth) / (self.titleButtons.count + 1);
    
    margin = MAX((int)margin, self.minMargin);
    
    for (NSInteger index = 0; index < self.layoutConstaints_H.count; index++) {
        NSLayoutConstraint *layoutConstraint = self.layoutConstaints_H[index];
        if (index == (self.layoutConstaints_H.count-1)) {
            layoutConstraint.constant = -margin;
        }else{
            layoutConstraint.constant = margin;
        }
    }
}

@end
